#include "movieRegister.h"
#include "startMovieHandler.h"
#include "reqParamParser.h"
#include "stringUtils.h"
#include "jsonUtils.h"
#include "httpOutput.h"
#include "playHandler.h"
#include "enterPlayRecordHandler.h"
#include "endPlayRecordHandler.h"
#include "MovieDownloader.h"

void MovieRegister::registerHandler(httplib::Server& svr)
{
	svr.Post("/startMovie", [](const httplib::Request& req, httplib::Response& res) {
		int64_t movieId = 0, dmId = 0;
		int test = 0;
		String body = StringUtils::utf8_2_wstr(req.body.c_str(), req.body.length());
		JsonDoc doc(rapidjson::kObjectType);
		doc.Parse(body.c_str());
		JsonUtils::loadLong(doc, L"id", movieId);
		JsonUtils::loadLong(doc, L"dmId", dmId);
		JsonUtils::loadInt(doc, L"test", test);
		StartMovieHandler handle;
		int id = handle(movieId, dmId, test);
		Char buf[MAX_PATH] = { 0 };
		swprintf_s(buf, L"{\"success\":true,\"data\":{\"id\":%d} }", id);
		HttpOutput::outputJson(buf,res);
	});

	svr.Put("/play", [](const httplib::Request& req, httplib::Response& res) {
		int64_t movieId = 0;
		int scene = 0;
		String body = StringUtils::utf8_2_wstr(req.body.c_str(), req.body.length());
		JsonDoc doc(rapidjson::kObjectType);
		doc.Parse(body.c_str());
		JsonUtils::loadLong(doc, L"movieId", movieId);
		JsonUtils::loadInt(doc, L"scene", scene);
		PlayHandler handle;
		handle(movieId, scene);
		HttpOutput::outputJson(L"{\"success\":true}", res);
	});

	svr.Put("/enterPlayRecord", [](const httplib::Request& req, httplib::Response& res) {
		int64_t id = 0, dmId = 0;
		String body = StringUtils::utf8_2_wstr(req.body.c_str(), req.body.length());
		JsonDoc doc(rapidjson::kObjectType);
		doc.Parse(body.c_str());
		JsonUtils::loadLong(doc, L"id", id);
		JsonUtils::loadLong(doc, L"dmId", dmId);
		EnterPlayRecordHandler handle;
		handle(id, dmId);
		HttpOutput::outputJson(L"{\"success\":true}", res);
	});

	svr.Put("/endPlayRecord", [](const httplib::Request& req, httplib::Response& res) {
		int64_t id = 0, dmId = 0;
		String body = StringUtils::utf8_2_wstr(req.body.c_str(), req.body.length());
		JsonDoc doc(rapidjson::kObjectType);
		doc.Parse(body.c_str());
		JsonUtils::loadLong(doc, L"id", id);
		JsonUtils::loadLong(doc, L"dmId", dmId);
		EndPlayRecordHandler handle;
		handle(id, dmId);
		HttpOutput::outputJson(L"{\"success\":true}", res);
	});

	svr.Post("/downloadMovie", [](const httplib::Request& req, httplib::Response& res) {
		int64_t id = 0;
		String body = StringUtils::utf8_2_wstr(req.body.c_str(), req.body.length());
		JsonDoc doc(rapidjson::kObjectType);
		doc.Parse(body.c_str());
		JsonUtils::loadLong(doc, L"movieId", id);
		MovieDownloader* downloader = new MovieDownloader(id);
		downloader->start();
		HttpOutput::outputJson(L"{\"success\":true}", res);
	});
}
